<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>我的聊天室</title>
  <style>
    * {
      padding: 0;
      margin: 0;
    }

    .container {
      width: 600px;
      margin: 0 auto;
      text-align: center;
    }

    #showmsg {
      margin-top: 10px;
      margin-bottom: 10px;
      width: 100%;
      height: 500px;
      overflow-x: hidden;
      overflow-y: auto;
      border: 1px solid #abcdef;
      border-radius: 18px;
      text-align: left;
    }
  </style>
</head>

<body>
  <div class="container">
    <div id="showmsg"></div>
    <div>
      <input type="text" id='cnt'> <button id='btn'>发送消息</button>
    </div>
  </div>
  <script src="./js/socket.io.min.js"></script>
  <script>
    let uname = prompt('请输入您的昵称！进入聊天室!')
    const client = io.connect('/')
    // if (uname && /[a-z]+/.test(uname)) {
    if (uname) {
      // 发送一个用户名
      client.emit('uname', uname)

      // 之前存储的数据
      client.on('allmsg', data => {
        if (data.length > 0) {
          let html = data.join('').replace(new RegExp(`【${uname}】`, 'g'), '【我】')
          document.querySelector('#showmsg').innerHTML = html
        }
      })

      client.on('msg', msg => {
        let div = document.createElement('div')
        div.innerHTML = msg.replace(new RegExp(`【${uname}】`, 'g'), '【我】')
        document.querySelector('#showmsg').appendChild(div)
      })
    }

    document.querySelector('#btn').addEventListener('click', clickHandler)
    function clickHandler() {
      client.emit('msg', cnt.value.trim())
      let arr = cnt.value.trim().match(/^(@.+)\s+/)
      if (!arr) {
        cnt.value = ''
      } else {
        cnt.value = arr[1] + ' ';
        cnt.focus();
      }
    }
    function clickme(name) {
      cnt.value = `@${name} `
      cnt.focus();
    }

  </script>

</body>

</html>